package cn.wangsy.contacts;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ServerThread extends Thread {

	private Socket socket = null;
	private boolean state = false; //登录状态
	private String password = null; 
	private boolean waitPassword = false;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			PrintWriter writer = new PrintWriter(socket.getOutputStream());
			String line = reader.readLine();
			while (!line.equals("BYE")) {
				if(state){ //登录
					if (line.startsWith("QUERY")){
						String[] cmds = line.split(" ");
						if(cmds.length >= 2){
							Contact contact = Data.getContact(cmds[1]);
							if(null == contact){
								writer.println("错误的用户号（或姓名）");
							}else{
								writer.println(contact.toString());
							}
						}else{
							writer.println("QUERY命令参数不正确，例如：QUERY 1");
						}
					}else{
						writer.println("error command");
					}
				}else if(waitPassword){
					if(line.equals(password)){
						state = true;
						writer.println("注册成功");
					}else{
						writer.println("密码错");
					}
				}else{
					if(line.startsWith("LOGIN")){
						String[] cmds = line.split(" ");
						if(cmds.length >= 2){
							password = Data.UserData.get(cmds[1]);
							if(password == null){
								writer.println("无此用户");
							}else{
								waitPassword = true;
								writer.println("密码：");
							}
						}else{
							writer.println("LOGIN命令参数不正确，例如：LOGIN 1");
						}
					}else{
						writer.println("error command");
					}
				}
				writer.flush();
				line = reader.readLine();
			}
			reader.close();
			writer.close();
		} catch (IOException e) {
			// e.printStackTrace();
		}
	}

}
